package com.crm.controller.saling;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crm.pojo.*;
import com.crm.service.repositoryService.IOlogService;
import com.crm.service.saling.*;
import com.crm.vo.CODetailsVO;
import com.crm.vo.DispatcherDetailProductCODetailVO;
import com.crm.vo.RefundDetailProductVO;
import com.crm.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by dr5hx on 2018/8/15
 */
@RequestMapping("saling")
@Controller
public class DetailsController {
    @Autowired
    private ContractService contractService;
    @Autowired
    private DispatcherService dispatcherService;
    @Autowired
    private DispatcherDetailService dispatcherDetailService;
    @Autowired
    private IOlogService iOlogService;
    @Autowired
    private CODetailsService coDetailsService;
    @Autowired
    private RefundService refundService;
    @Autowired
    private RefundDetailService refundDetailService;
    @Autowired
    private PlaningBackService planingBackService;

    {

    }

    /**
     * 转发到细节页面,并非所有存在的都以被显示
     *
     * @param id
     * @return
     */
    @GetMapping("details")
    public ModelAndView toDialog(Long id) {
        try {
            if (id != null & contractService.getLoadContractVO(id) != null) {
                ModelAndView modelAndView = new ModelAndView("saling/contractAllDetails");
                modelAndView.addObject("contractVo", contractService.getLoadContractVO(id));
                return modelAndView;
            } else {
                return new ModelAndView("404");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ModelAndView("404");
        }
    }

    /**
     * 通过id查询联系人
     *
     * @param id
     * @return
     */
    @PostMapping("findContactById")
    @ResponseBody
    public Contact findContactById(Long id) {
        try {
            return contractService.findContactById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 添加一个待审核的出库单
     *
     * @return
     */
    @PostMapping("toAddOutboundOrder")
    @ResponseBody
    public Result toAddOutboundOrder(Long contractId, Long empno, String iotitle, String rows) {
        try {
            if (rows != null && contractId != null && empno != null) {
                JSONArray jsonArray = JSONArray.parseArray(rows);
                Dispatcher dispatcher = new Dispatcher();
                dispatcher.setFkOrderId(new BigDecimal(contractId.toString()));
                dispatcher.setDispatcherState("未发货");
                dispatcher.setFkDispatcherCustomer(new Date());
                dispatcher.setDispatcherIsDel("否");
                Dispatcher d = dispatcherService.saveDispatcher(dispatcher);
                List<DispatcherDetail> dispatcherDetailList = new ArrayList<>();
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject productionDetail = jsonArray.getJSONObject(i).getJSONObject("productionDetail");
                    JSONObject coDetail = jsonArray.getJSONObject(i).getJSONObject("coDetail");
                    DispatcherDetail dispatcherDetail = new DispatcherDetail();
                    // 0未审核1发货中2完成3部分退货4全部退货
                    dispatcherDetail.setFkDispatcherId(new BigDecimal(0));
                    dispatcherDetail.setDispatcher(d);
                    dispatcherDetail.setProductAccount(new BigDecimal(coDetail.get("cOAmount").toString()).subtract(new BigDecimal(coDetail.get("cOCompleteAccount").toString())).subtract(new BigDecimal(coDetail.get("productType").
                            toString())).subtract(new BigDecimal(coDetail.get("fkOrderId").toString())));
                    dispatcherDetail.setDispatcherDetailsIsDel("否");
                    dispatcherDetail.setPId(new BigDecimal(productionDetail.get("pid").toString()));
                    dispatcherDetailList.add(dispatcherDetail);
                    CODetail c = coDetailsService.getOneCODetail(Long.parseLong(coDetail.get("cOId").toString())).getCoDetail();
                    c.setFkOrderId(c.getFkOrderId().add(new BigDecimal(coDetail.get("cOAmount").toString()).subtract(new BigDecimal(coDetail.get("cOCompleteAccount").toString())).subtract(new BigDecimal(coDetail.get("productType").
                            toString())).subtract(new BigDecimal(coDetail.get("fkOrderId").toString()))));
                    coDetailsService.saveEditCODetail(c);
                }
                dispatcherDetailService.saveDispatcherDetailList(dispatcherDetailList);
                Inandoutlog inandoutlog = new Inandoutlog();
                inandoutlog.setHandmanId(empno);
                inandoutlog.setIotitle(iotitle);
                inandoutlog.setInandoutlogIsDel("否");
                inandoutlog.setIotype(1L);
                inandoutlog.setIoDate(new Date());
                inandoutlog.setIoDispatherId(d.getDispatcherId());
                iOlogService.addIOlog(inandoutlog);

                return Result.SUCCESS;
            } else {
                return new Result("存在不正确的数据");
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return new Result("出现异常");

        }
    }

    /**
     * 获取最大的可发货数量
     *
     * @param cOId
     * @return
     */
    @PostMapping("getNumberForDispatcher")
    @ResponseBody
    public Long getNumberForDispatcher(Long cOId) {
        try {
            CODetail coDetail = coDetailsService.getOneCODetail(cOId).getCoDetail();
            return coDetail.getCOAmount().subtract(coDetail.getCOCompleteAccount()).subtract(coDetail.getFkOrderId()).longValue();
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }

    /**
     * 获取发货详单列表
     *
     * @param contractId
     * @return
     */
    @PostMapping("getDispatcherDetailListByContractId")
    @ResponseBody
    public List<DispatcherDetailProductCODetailVO> getDispatcherDetailListByContractId(Long contractId) {
        try {
            return dispatcherDetailService.getDispatcherDetailList(contractId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取退单总数量
     *
     * @param cOId
     * @return
     */
    @PostMapping("getALLNumberForRefund")
    @ResponseBody
    public Long getALLNumberForRefund(Long cOId) {
        try {
            CODetail coDetail = coDetailsService.getOneCODetail(cOId).getCoDetail();
            return coDetail.getCOCompleteAccount().longValue();
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }

    /**
     * 添加退款数据
     *
     * @param contractId
     * @param empno
     * @param refundTitle
     * @param rows
     * @return
     */
    @PostMapping("toAddRefundOrderList")
    @ResponseBody
    public Result toAddRefundOrderList(Long contractId, Long empno, String refundTitle, String rows) {
        try {
            if (rows != null && contractId != null && empno != null) {
                Contract contract = contractService.getLoadContractVO(contractId).getContract();
                contract.setContractIsRefund("有");
                contractService.saveContract(contract);
                Refund refund = new Refund();
                refund.setRefundTopic(refundTitle);
                refund.setRefundTime(new Date());
                //设置经手人
                refund.setFkRefundCustomerId(new BigDecimal(empno));
                refund.setRefundAlreadyMoney(new BigDecimal(0));
                refund.setRefundIsDel("否");
                refund.setFkRefundContractId(new BigDecimal(contractId.toString()));
                refund.setRefundState("待完成");
                refund.setRefundMoney(new BigDecimal(0));
                Refund r = refundService.saveARefund(refund);
                JSONArray jsonArray = JSONArray.parseArray(rows);
                List<RefundDetail> refundDetailList = new ArrayList<>();
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject coDetail = jsonArray.getJSONObject(i).getJSONObject("coDetail");
                    JSONObject productionDetail = jsonArray.getJSONObject(i).getJSONObject("productionDetail");
                    RefundDetail refundDetail = new RefundDetail();
                    refundDetail.setRefund(refund);
                    //设置这个字段为审核字段0未审核，1审核成功 入库
                    refundDetail.setFkRefundId(new BigDecimal(0));
                    refundDetail.setRefundDetailsMoney(new BigDecimal(coDetail.get("cOCompleteAccount").toString()).multiply(new BigDecimal(coDetail.get("cOPrice").toString())));
                    refundDetail.setRefundDetailsIsDel("否");
                    refundDetail.setRefundDetailsAmount(new BigDecimal(coDetail.get("cOCompleteAccount").toString()));
                    refundDetail.setFkRefundProductId(new BigDecimal(productionDetail.get("pid").toString()));
                    r.setRefundMoney(r.getRefundMoney().add(new BigDecimal(coDetail.get("cOCompleteAccount").toString()).multiply(new BigDecimal(coDetail.get("cOPrice").toString()))));
                    refundDetailList.add(refundDetail);
                    CODetail c = coDetailsService.getOneCODetail(Long.parseLong(coDetail.get("cOId").toString())).getCoDetail();
                    if (c.getCOAmount().equals(new BigDecimal(coDetail.get("cOCompleteAccount").toString()))) {
                        c.setCOState("全部退货");
                    } else {
                        c.setCOState("部分退货");
                        c.setCOAmount(c.getCOAmount().subtract(new BigDecimal(coDetail.get("cOCompleteAccount").toString())));
                        c.setCOCompleteAccount(c.getCOCompleteAccount().subtract(new BigDecimal(coDetail.get("cOCompleteAccount").toString())));
                        c.setCOMoney(c.getCOAmount().multiply(c.getCOPrice()));
                    }
                    coDetailsService.saveEditCODetail(c);
                    PlaningBack planingBack = new PlaningBack();
                    planingBack.setPlaningBackTime(new Date());
                    planingBack.setPlaningBackIsBack("否");
                    planingBack.setPlaningBackIsDel("否");
                    planingBack.setFkPlaningBackOrderId(new BigDecimal(contractId.toString()));
                    planingBack.setPlaningBackMoney(new BigDecimal("-" + coDetail.get("cOCompleteAccount").toString()).multiply(new BigDecimal(coDetail.get("cOPrice").toString())));
                    planingBackService.savePlaningBackData(planingBack);
                }
                refundService.saveARefund(r);
                Inandoutlog inandoutlog = new Inandoutlog();
                inandoutlog.setHandmanId(empno);
                inandoutlog.setIotitle(refundTitle);
                inandoutlog.setInandoutlogIsDel("否");
                inandoutlog.setIotype(3L);
                inandoutlog.setIoDate(new Date());
                inandoutlog.setIoDispatherId(refund.getRefundId());
                iOlogService.addIOlog(inandoutlog);
                refundDetailService.saveRefundDetailList(refundDetailList);
                return Result.SUCCESS;
            } else {
                return new Result("参数解析失败");
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return new Result("exception happened");

        }

    }


    /**
     * 显示合同对应的详单可发货列表
     *
     * @param contractId
     * @return
     */
    @PostMapping("loadDispatcherCODetailsList")
    @ResponseBody
    public List<CODetailsVO> showDispatcherCODetailsList(Long contractId) {
        try {
            Long cid = contractId == null ? 0L : contractId;
            List<CODetailsVO> list = coDetailsService.showOrderDetailsList(cid);
            List<CODetailsVO> coDetailsVOList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                CODetail coDetail = list.get(i).getCoDetail();
                if (!coDetail.getCOAmount().equals(coDetail.getFkOrderId().add(coDetail.getCOCompleteAccount()).add(new BigDecimal(coDetail.getProductType().toString())))) {
                    coDetailsVOList.add(list.get(i));
                }
            }
            return coDetailsVOList;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 显示合同对应的详单可退货列表
     *
     * @param contractId
     * @return
     */
    @PostMapping("loadRefundCODetailsList")
    @ResponseBody
    public List<CODetailsVO> showRefundCODetailsList(Long contractId) {
        try {
            Long cid = contractId == null ? 0L : contractId;
            List<CODetailsVO> list = coDetailsService.showOrderDetailsList(cid);
            List<CODetailsVO> coDetailsVOList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                CODetail coDetail = list.get(i).getCoDetail();
                if (!coDetail.getCOCompleteAccount().equals(new BigDecimal(0))) {
                    coDetailsVOList.add(list.get(i));
                }
            }
            return coDetailsVOList;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 转发去退货细节
     *
     * @return
     */
    @GetMapping("toRefundDetailProductVO")
    public String toRefundDetailProductVO() {
        return "saling/refundDetailList";
    }

    /**
     * 显示退货细节列表
     *
     * @param page
     * @param rows
     * @return
     */
    @PostMapping("getRefundDetailProductVO")
    @ResponseBody
    public Map getRefundDetailProductVO(int page, int rows) {
        try {
            List<RefundDetailProductVO> list = refundDetailService.getRefundDetailProductVO(page, rows);
            Long count = refundDetailService.getRefundDetailCount();
            Map map = new HashMap();
            map.put("rows", list);
            map.put("total", count);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
